<template>
  <div :class="{ hidden: hidden }" class="pagination-container">
    <el-pagination
      :background="background"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :layout="layout"
      :page-sizes="pageSizes"
      :pager-count="pagerCount"
      :total="total"
      v-bind="$attrs"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 只有一页的时候是否显示：  hide-on-single-page-->
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { ElPagination } from 'element-plus'

interface Props {
  total: number
  page?: number
  limit?: number
  // 显示多少个分页按钮，影响分页total
  pageSizes?: number[]
  // 移动端页码按钮的数量端默认值5
  pagerCount?: number
  layout?: string
  background?: boolean
  autoScroll?: boolean
  hidden?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  page: 1,
  limit: 10,
  pageSizes: () => [10, 30, 50, 100],
  pagerCount: document.body.clientWidth < 992 ? 5 : 7,
  layout: 'total, sizes, prev, pager, next, jumper',
  background: true,
  autoScroll: true,
  hidden: false
})

const emit = defineEmits(['update:page', 'update:limit', 'pagination'])

const currentPage = computed({
  get() {
    return props.page
  },
  set(val) {
    emit('update:page', val)
  }
})

const pageSize = computed({
  get() {
    return props.limit
  },
  set(val) {
    emit('update:limit', val)
  }
})

const handleSizeChange = (val: number) => {
  console.log('Pagination - handleSizeChange:', {
    val,
    currentPage: currentPage.value,
    total: props.total
  })
  let newPage = currentPage.value
  if (currentPage.value * val > props.total) {
    newPage = 1
    emit('update:page', 1)
  }
  console.log('Pagination - emit pagination:', { page: newPage, limit: val })
  emit('pagination', { page: newPage, limit: val })
}

const handleCurrentChange = (val: number) => {
  console.log('Pagination - handleCurrentChange:', { val, pageSize: pageSize.value })
  emit('pagination', { page: val, limit: pageSize.value })
}
</script>

<style scoped lang="scss">
:deep {
  .el-select .el-input.is-focus .el-input__inner {
    border-color: #7c0a03;
  }
  .el-select .el-select-dropdown__item {
    color: #7c0a03 !important;
  }
  .el-select .el-select-dropdown__item.selected {
    color: #7c0a03 !important;
  }
  .el-pagination.is-background .el-pager li.active {
    background-color: #7c0a03 !important;
  }
  .el-pagination__total {
    display: none !important;
  }
}

.pagination-container {
  background: #fff;
  // padding: 32px 16px;
}
.pagination-container.hidden {
  display: none;
}
</style>
